import socket
import _thread
import ujson
import network
from oledprint import getI2Cstatue,threaded_print,OLEDPrinter
w=getI2Cstatue()
if w :
    oled_printer = OLEDPrinter(w)  
    global print  # 声明 print 为全局变量
    def print(*args, **kwargs):
        threaded_print(oled_printer,*args, **kwargs)
class WebUIManager:
    def __init__(self, config_file, network_manager):
        self.config_file = config_file
        self.network_manager = network_manager

    def url_decode(self, encoded_str):
        result = ''
        i = 0
        while i < len(encoded_str):
            if encoded_str[i] == '%':
                try:
                    result += chr(int(encoded_str[i + 1:i + 3], 16))
                    i += 3
                except:
                    result += '%'
                    i += 1
            elif encoded_str[i] == '+':
                result += ' '
                i += 1
            else:
                result += encoded_str[i]
                i += 1
        return result

    def parse_qs(self, query_string):
        data = {}
        if not query_string:
            return data

        pairs = query_string.split('&')
        for pair in pairs:
            if '=' in pair:
                key, value = pair.split('=', 1)
                data[self.url_decode(key)] = self.url_decode(value)
        return data

    def save_config(self, ssid, password, upload_url):
        with open(self.config_file, "w") as f:
            ujson.dump({"ssid": ssid, "password": password, "upload_url": upload_url}, f)

    def web_ui(self):
        html = """
        <html>
            <head><title>WiFi与服务器配置</title></head>
            <body>
                <h1>上传 WiFi 配置与服务器地址</h1>
                <form method="POST" action="/config">
                    <label for="ssid">WiFi SSID:</label><br>
                    <input type="text" id="ssid" name="ssid" required><br><br>
                    <label for="password">WiFi 密码:</label><br>
                    <input type="password" id="password" name="password" required><br><br>
                    <label for="upload_url">上传 URL:</label><br>
                    <input type="text" id="upload_url" name="upload_url" value="http://192.168.1." placeholder="http://192.168.1.xxx:xxxx" required><br><br>
                    <input type="submit" value="保存配置">
                </form>
            </body>
        </html>
        """
        return html

    def handle_request(self, client_socket):
        try:
            request = client_socket.recv(1024).decode('utf-8')
            print("Request:", request)

            if 'GET / ' in request:
                response = (
                    'HTTP/1.1 200 OK\r\n'
                    + 'Content-Type: text/html\r\n'
                    + '\r\n' + self.web_ui()
                )
                client_socket.send(response.encode('utf-8'))

            elif 'POST /config' in request:
                body = request.split('\r\n\r\n', 1)[1]
                form_data = self.parse_qs(body)

                ssid = form_data.get('ssid', '')
                password = form_data.get('password', '')
                upload_url = form_data.get('upload_url', '')
                print(f"从网页加载配置: SSID={ssid}, Password={password}, Upload URL={upload_url}")
                self.save_config(ssid, password, upload_url)
                client_socket.send('HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n配置已保存')
                self.network_manager.connect_wifi(ssid, password)
            client_socket.close()
        except Exception as e:
            print("请求处理错误:", e)
            client_socket.close()

    def start_web_server(self):
        addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
        server_socket = socket.socket()
        server_socket.bind(addr)
        server_socket.listen(5)
        ap = network.WLAN(network.AP_IF)
        print('connect ap & Web to config:', ap.ifconfig()[0])

        while True:
            client_socket, _ = server_socket.accept()
            _thread.start_new_thread(self.handle_request, (client_socket,))
